﻿using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Windows.Forms;
using BtcPay.Properties;
using Info.Blockchain.API;
using Info.Blockchain.API.BlockExplorer;
using Info.Blockchain.API.Receive;

namespace BtcPay
{
    public partial class PayDialog : Form
    {
        private readonly PayAdress pa;
        private string curAmount;
        private readonly Feature f;
        private Timer timer = new Timer();

        public PayDialog(PayAdress pa, Feature f)
        {
            this.pa = pa;

            this.f = f;
            InitializeComponent();

            QRCodeGenerator qrGenerator = new QRCodeGenerator();
            QRCodeGenerator.QRCode qrCode = qrGenerator.CreateQrCode(pa.ToString().Replace("[featureId]", f.Id.ToString()), QRCodeGenerator.ECCLevel.H);
            
            qrPb.Image = qrCode.GetGraphic(20);

            amountLbl.Text = "Amount: " + pa.Amount.ToString() + " BTC";
            addressLbl.Text = "Address: " + pa.ToAddress;
            featureLbl.Text = "Feature: " + f.ToString();

            timer.Tick += payedTimer_Tick;
        }

        private void linkLl_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            var uri = pa.ToString().Replace("[featureId]", f.Id.ToString());
            Process.Start(uri);
        }

        private void payedTimer_Tick(object sender, EventArgs e)
        {
            try
            {
                var blockExplorer = new BlockExplorer();
                var ad = blockExplorer.GetAddress(pa.ToAddress);

                var c = ad.FinalBalance;

                var unconfirmedTxs = blockExplorer.GetUnconfirmedTransactions();
                foreach (Transaction unconfTx in unconfirmedTxs)
                {
                    foreach (var item in unconfTx.Outputs)
                    {
                        if (item.Value.ToString() == pa.Amount)
                        {
                            statusPb.Image = Resources.notification_done;
                            okBtn.Enabled = true;
                            timer1.Stop();
                            countLbl.Text = "60";
                            countLbl.Visible = false;
                            payedTimer.Stop();
                        }
                    }
                }
            }
            catch (APIException ex)
            {
                MessageBox.Show("Blockchain exception: " + ex.Message);
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            countLbl.Text = (int.Parse(countLbl.Text)-1).ToString();
            if (countLbl.Text == "0")
            {
                DialogResult = System.Windows.Forms.DialogResult.Cancel;
                timer1.Stop();
            }
        }
    }
}